﻿using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace MES.Core.Extension
{
    public class AddDBHeaderFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
            var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
            var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);
            var apiVersionParam = operation.Parameters?.FirstOrDefault(p => p.Name == "api-version");
            if (apiVersionParam != null)
            {
                apiVersionParam.Description = "此参数用于指定 API 的版本号，在请求 URL 中以查询字符串的形式出现，例如“?api-version=1.0”，便于服务端依据该版本号进行相应的业务逻辑处理，保障不同版本 API 的准确调用。";
            }
            if ((!context.ApiDescription.RelativePath.Contains("api/LibraryManager/AddConnectionPool")) && !context.ApiDescription.RelativePath.Contains("api/LibraryManager/CreateTable") && !context.ApiDescription.RelativePath.Contains("api/Generate"))
            {
                if (operation.Parameters == null)
                    operation.Parameters = new List<OpenApiParameter>();

                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "databaseName",
                    In = ParameterLocation.Header,
                    Description = "租户数据库名称，例如“mes”此参数用于指定数据库名称，便于服务端依据该名称进行相应的业务逻辑处理，保障不同数据库的准确调用。",
                    Required = true,
                    Schema = new OpenApiSchema
                    {
                        Type = "string",
                    }
                });
            }

            if (isAuthorized && !allowAnonymous)
            {
                //加入JWT
            }
        }
    }
}
